package controllers

import (
	"context"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"

	"shortUrl/logic"
	"shortUrl/models"
	"shortUrl/pkg/validate"
)
type ContraollerUrl struct{
	Logic logic.LoginUrler
}
func NewContraollerUrl(logic logic.LoginUrler)*ContraollerUrl{
	return &ContraollerUrl{
		Logic: logic,
	}
}
func (u *ContraollerUrl) CreateUrl(c *gin.Context) {
	// 获取参数数据
	var req models.CreateUrlRequset
	if err := c.ShouldBind(&req); err != nil{
		fmt.Println(req,"req")
		errs,ok := err.(validator.ValidationErrors)
		if !ok {
			ResponseError(c, CodeInvalidParam)
			return 
		}
		for _,v := range validate.RemoveTopStruct(errs.Translate(validate.Trans)){
			ResonseErrorWithMsg(c,CodeInvalidParam,v )
		}
		
	}
	// 调用逻辑层
	res, err := u.Logic.CreateUrl(context.Background(),req)
	if err != nil{
		ResponseError(c, CodeInvalidParam)
		return 
	}

	ResponseSuccess(c, CodeSuccess, "创建成功", map[string]string{
		"original_url": res.OriginalUrl,
		"short_url": res.ShortCodeUrl,
	})
	
}

func (u *ContraollerUrl) RedirectUrl(c *gin.Context){
	shortcode := c.Param("shortCode")
	if shortcode == ""{
		ResponseError(c, CodeInvalidParam)
		return 
	}
	originalUrl,err :=u.Logic.GetOriginalURL(context.Background(),shortcode)
	if err != nil{
		ResponseError(c, CodeOriginalUrlGet)
		return 
	}
	c.Redirect(http.StatusMovedPermanently,originalUrl)
}